package com.woniu.atms.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.atms.util.Audience;
import com.woniu.atms.util.Code;
import com.woniu.atms.util.JwtUtil;
import com.woniu.atms.util.ResponseResult;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 张奇
 * @title: AftJWTFilter
 * @projectName g5_atms
 * @description: TODO 后台用户的过滤器 访问后台路径时调用
 * @date 2022/1/24 12:17
 */
public class AftJWTFilter implements Filter {
    @Resource
    private Audience audience;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = ((HttpServletRequest) request);
        HttpServletResponse resp = (HttpServletResponse) response;
        String path = req.getRequestURI();


        //设置放行页面 登录页面放行
        if (path.indexOf("login")!=-1) {

            System.out.println("==========登录放行");
            chain.doFilter(request, response); // 排除的url
        } else {
            //设置后台过滤条件

            String token = req.getHeader("aft_token");
            System.out.println("==========后台过滤，token:"+token);
            System.out.println("==========后台过滤，audience:"+audience);
            if (token == null||"null".equals(token)||token.trim()==""|| !JwtUtil.verifyJwt(token, audience)) {
                ResponseResult result = new ResponseResult<>(Code.TOKEN_ERROR, "登录信息失效，请重新登录");
                ObjectMapper objectMapper = new ObjectMapper();
                resp.setCharacterEncoding("utf-8");
                resp.getWriter().print(objectMapper.writeValueAsString(result));
                resp.getWriter().close();
                return;
            }else {
                chain.doFilter(request, response); // 排除的url
            }

        }
        }

}
